package dao

import com.db4o.ObjectContainer
import com.db4o.query.Query
import scala.collection.JavaConversions._

trait CommonDAO[T] {
  
  def count[T]()(implicit s:Session):Int = {
    val q = s.get.query()
    q.constrain(classOf[Class[T]])
    q.execute().size()
  }
  
  def findAll[T]()(implicit s:Session): Option[List[T]] = {
    import scala.collection.JavaConversions._
    val query:Query = s.get.query()
    query.constrain(classOf[Class[T]])
    val result:List[T] = query.execute().toList //XXX
    if(!result.isEmpty){
      Some(result)
    } else {
      None 
    }
  }
  
  
  def save(o:Any)(implicit s:Session):Boolean = {
    s.get.store(o)
    s.get.ext().refresh(o, Integer.MAX_VALUE)
    s.get.commit()
    true
  }
  
  def update(o:Any)(implicit s:Session):Boolean = {
    if(s.get.ext().getID(o) != 0){
      s.get.store(o)
      true
    } else {
      play.Logger.error("Object not present in the DB")
      throw new Exception()
    }
  }
  
  def delete(o:Any)(implicit s:Session):Boolean = {
    s.get.delete(o)
    s.get.commit()
    true
  }
}

class Session (dbServer:ObjectContainer) {
  //Db4o Session
  private var _session:ObjectContainer = null
  def connect() = {
    if(dbServer != null){
      _session = dbServer.ext.openSession()
    }
  }
  def disconnect() = {
    if(_session != null){
      if(_session.close()){
        _session = null
      }
    }
  }
  
  def get = _session
  
}
